package cn.demomaster.quickdb.view;

import android.content.Context;
import android.os.Build;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import cn.demomaster.quickdb.R;
import cn.demomaster.quickdb.adapter.TableAdapter;
import cn.demomaster.quickdb.mapper.MapperManager;
import cn.demomaster.quickdb.model.ColumnInfo;

public class TableView extends HorizontalScrollView {
    public TableView(@NonNull Context context) {
        super(context);
        init();
    }

    public TableView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public TableView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public TableView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init();
    }

    LinearLayout rootLinearLayout;
    LinearLayout tableHeaderView;
    RecyclerView bodyRecyclerView;

    public void init() {
        setOverScrollMode(OVER_SCROLL_NEVER);
        if (rootLinearLayout == null) {
            rootLinearLayout = new LinearLayout(getContext());
            addView(rootLinearLayout);
            rootLinearLayout.setOrientation(LinearLayout.VERTICAL);
            tableHeaderView = new LinearLayout(getContext());
            //tableTitleRow.setOverScrollMode(OVER_SCROLL_NEVER);
            rootLinearLayout.addView(tableHeaderView);
            bodyRecyclerView = new RecyclerView(getContext());
            bodyRecyclerView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            bodyRecyclerView.setOverScrollMode(OVER_SCROLL_NEVER);
            rootLinearLayout.addView(bodyRecyclerView);
        }

        initAdapter();
    }

    String[] mTitles;

    public void setTitles(String[] titles) {
        this.mTitles = titles;
        setUpHeaderData(titles);
    }


    public void setColumns(List<ColumnInfo> columnInfos){
        mTitles = new String[columnInfos.size()];
        for (int i = 0; i < columnInfos.size(); i++) {
            mTitles[i] = TextUtils.isEmpty(columnInfos.get(i).getColumnComment()) ? columnInfos.get(i).getColumnName() :columnInfos.get(i).getColumnComment();
        }
        setUpHeaderData(mTitles);
    }

    private void setUpHeaderData(String[] titles) {
        //tableHeaderView.setData(titles);
        tableHeaderView.removeAllViews();
        if (mTabledapter != null) {
            ViewGroup linearLayout = mTabledapter.getRowLayout(-1);
            tableHeaderView.addView(linearLayout);
            for (int i = 0; i < titles.length; i++) {
                View view = mTabledapter.getCellView(null, -1);
                TextView textView = view.findViewById(R.id.tv_text);
                textView.setText(titles[i]);
                if (view.getLayoutParams() == null) {
                    linearLayout.addView(view);
                } else {
                    linearLayout.addView(view, view.getLayoutParams());//mTabledapter.mRowAdapter.getCellLayoutParams(-1, i));
                }
                mTabledapter.bindCellViewData(-1, i, linearLayout, view);
            }
            mTabledapter.bindRowViewData(-1, linearLayout);
            linearLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    linearLayout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                    mTabledapter.notifyDataSetChanged();
                }
            });
        }
    }

    TableAdapter mTabledapter = null;

    public void setAdapter(TableAdapter adapter) {
        //mTabledapter.setRowAdapter(tableRowAdapter);
        this.mTabledapter = adapter;
        this.bodyRecyclerView.setAdapter(adapter);
    }

    public void initAdapter() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        //设置布局管理器
        //设置为垂直布局，这也是默认的
        layoutManager.setOrientation(RecyclerView.VERTICAL);
        bodyRecyclerView.setLayoutManager(layoutManager);
        //设置Adapter
        bodyRecyclerView.setAdapter(mTabledapter);

        //mTabledapter = new TableAdapter2(getContext());
//        if (mTabledapter.mRowAdapter != null) {
//            mTabledapter.setRowAdapter(mTabledapter.mRowAdapter);
//        }
    }

//    public void setData1(List<String[]> stringList) {
//        mTabledapter.updateList(stringList);
//        // bodyRecyclerView.setAdapter(tableAdapter);
//    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        boolean tResult = super.onTouchEvent(ev);
        if (tResult) {
            bodyRecyclerView.dispatchTouchEvent(ev);
        }
        return tResult;
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        //return super.onInterceptTouchEvent(ev);
        return true;
    }
    List<ColumnInfo> mColumnInfos = new ArrayList<>();
    public <T> void setData(List<T> modelList, Class<T> clazz) {
        mColumnInfos = MapperManager.getInstance().getMapper(clazz).getColumnInfoList();
        mTitles = new String[mColumnInfos.size()];
        for (int i = 0; i < mColumnInfos.size(); i++) {
            mTitles[i] = TextUtils.isEmpty(mColumnInfos.get(i).getColumnComment()) ? mColumnInfos.get(i).getColumnName() :mColumnInfos.get(i).getColumnComment();
        }
        setUpHeaderData(mTitles);
        if (mTabledapter != null) {
            List<String[]> stringList = new ArrayList<>();
            for (int i = 0; i < modelList.size(); i++) {
                T t = modelList.get(i);
                String[] strings = new String[mColumnInfos.size()];
                for (int j = 0; j < mColumnInfos.size(); j++) {
                    String fieldName = mColumnInfos.get(j).getFieldName();
                    try {
                        strings[j] = String.valueOf(MapperManager.getInstance().getMapper(clazz).getFieldValue(t,fieldName));
//                        String valueFormat = mColumnInfos.get(j).getValueFormat();
//                        if(!TextUtils.isEmpty(valueFormat)){
//                            strings[j] = String.format(valueFormat,strings[j]);
//                        }
                        String fieldValue =  mTabledapter.formatColumnValue(MapperManager.getInstance().getMapper(clazz).tableName,mColumnInfos.get(j),strings[j]);
                        if(!TextUtils.isEmpty(fieldValue)){
                            strings[j] = fieldValue;
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
                stringList.add(strings);
            }
            mTabledapter.updateList(stringList);
        }
    }

    public <T> void setData2(List<String[]> modelList) {
        List<String[]> stringList = modelList;
        setUpHeaderData(mTitles);
        //setData1(stringList);
    }

    /**
     * 字段排序
     *
     * @param tableColumns
     * @return
     */
    private List<ColumnInfo> sortColumn(List<ColumnInfo> tableColumns) {
        LinkedHashMap<String, ColumnInfo> map = new LinkedHashMap<>();
        for (ColumnInfo tableColumn : tableColumns) {
            map.put(tableColumn.getColumnName(), tableColumn);
        }

        //把id排序在最左边
        if (map.containsKey("id")) {
            LinkedHashMap<String, ColumnInfo> map2 = new LinkedHashMap<>();
            ColumnInfo tableColumn = map.get("id");
            map2.put("id", tableColumn);
            map2.putAll(map);
            map = map2;
        }

        List<ColumnInfo> tableColumns_c = new ArrayList<>();
        for (Map.Entry entry : map.entrySet()) {
            tableColumns_c.add((ColumnInfo) entry.getValue());
        }

        return tableColumns_c;
    }

}
